<?php

namespace app\index\controller;

use app\common\controller\HomeBase;
use think\Db;

class Index extends HomeBase {

    public function index() {
        $topic_id = input('param.topic_id');
        
        if (!isset($topic_id))
            abort(404, '缺少必要参数');
        
        session('topic_id', $topic_id);  //把topic_id 存在session
        
        $topic_log = array_reduce(Db::name('TopicLog')->where(['user_id'=>session('user_id'),'topic_id'=>session('topic_id')])->select(), function(&$newArray,$v){$newArray[$v['topic_t']]=$v; return $newArray;});

        return $this->fetch($topic_id, [
            'log' => $topic_log
        ]);
    }

    //实时推送题目
    public function form() {
        if ($this->request->isPost()) {
            $data = input('post.');

            $user_id = session('user_id');

            if (!isset($data['topic_t']))
                $this->error('非法提交！');

            foreach ($data['topic_t'] as $k => $v) {  //拿出题目的结果
                $array = [
                    'topic_id' => session('topic_id'),
                    'topic_t' => $k,
                    'topic_v' => $v,
                    'user_id' => $user_id,
                    'add_time' => time()
                ];
            }

           
            
            //查找该会员有没有做过这题 如果做过就更新 没有则新增
            $res = Db::name('topic_log')->where(['user_id' => $user_id,'topic_id'=>$array['topic_id'], 'topic_t' => $array['topic_t']])->find();
            if ($res) {  //更新
                if (Db::name('topic_log')->where(['id' => $res['id']])->update(['topic_v' => $array['topic_v']]) !== false) {
                    $this->success('', '', $array['topic_v']);
                } else {
                    $this->error('程序异常，请稍后再试！');
                }
            } else { //插入
                if (Db::name('topic_log')->insert($array)) {
                    $this->success('', '', $array['topic_v']);
                } else {
                    $this->error('程序异常，请稍后再试！');
                }
            }
        }
    }

    //删除的题目
    public function del() {
        if ($this->request->isPost()) {
            $data = input('post.');

            $user_id = session('user_id');

            if (!isset($data['topic_t']))
                $this->error('非法提交！');

            foreach ($data['topic_t'] as $k => $v) {  //拿出题目的结果
                $array = [
                    'topic_id' => session('topic_id'),
                    'topic_t' => $k,
                    'topic_v' => $v
                ];
            }

            //删除该用户做的题目
            if(Db::name('topic_log')->where(['user_id' => $user_id,'topic_id'=>$array['topic_id'],'topic_t' => $array['topic_t']])->delete() !== false){
                $this->success();
            }else{
                $this->error('程序异常，请稍后再试！');
            }
        }
    }

}
